package it.gestionedocumentale.struts.action.download;

import it.gestionedocumentale.model.Documento;
import it.gestionedocumentale.model.Utente;
import it.gestionedocumentale.spring.service.MyServiceFactory;
import it.gestionedocumentale.struts.form.DocumentoForm;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class ConfermaDownloadDocumentoAction extends Action {
	private static Log log = LogFactory.getLog(ConfermaDownloadDocumentoAction.class);
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		Utente utenteSession = (Utente) request.getSession().getAttribute("utenteSession");
		if(utenteSession == null) {
			return mapping.findForward("notInSession");
		}
		
		DocumentoForm documentoForm=(DocumentoForm) form;
		Documento documento = 
			MyServiceFactory.getDocumentoService().findById(documentoForm.getIdDocumento());
		
		String nomefile=documento.getNomeDocumento();
		String pathFile=documento.getPath();
		
        File myFile = null;
        OutputStream outStream = null;
        FileInputStream inStream = null;
        try {

			myFile=new File(pathFile+"/"+nomefile);
			outStream = response.getOutputStream();
			inStream = new FileInputStream(myFile);
			
			response.setContentType ("application/octet-stream");
			response.setContentLength((int)myFile.length());
			response.setHeader("Content-Disposition","attachment; filename=\""+nomefile);
			response.setHeader("Cache-Control", "no-cache");
			
			byte[] buffer = new byte[8192];
			int sizeRead = 0;
			
			while ((sizeRead = inStream.read(buffer, 0, buffer.length)) > 0) {
			    outStream.write(buffer, 0, sizeRead);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			return mapping.findForward("error");
		} finally{
			inStream.close();
			outStream.close();
			response.getOutputStream().close();
		}
		
		return super.execute(mapping, form, request, response);
	}
}
